import java.io.*;
import java.net.*;

class submitJob
{
 	public static void main(String args[]) throws Exception
 	{
		int pid=5000;
		if(args.length>0) {
			try {
				pid = Integer.parseInt(args[0]);
			} catch (NumberFormatException e) {
				System.err.println("Argument" + " must be an integer");
				System.exit(1);
			}
		}
	// create a Job
		Job job = createJob();
		
		try {

		  	String answer;
			Socket clientSocket;
			ObjectOutputStream outToServer;
			ObjectInputStream inFromServer;
			BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));

			clientSocket = new Socket("localhost", pid);
		  	outToServer = new ObjectOutputStream(clientSocket.getOutputStream());
		  	inFromServer = new ObjectInputStream(clientSocket.getInputStream());

		  	outToServer.writeObject(new String("SubmitJob"));
		  	outToServer.writeObject(job);
		  	answer = (String) inFromServer.readObject();
		  	printStream(answer);
      		
			System.out.println("Do you want to purchase the vms (y/n)");
	  		String userResponse=inFromUser.readLine();
	  		if(userResponse.equals("y")) {
	  			outToServer.writeObject(new String("PurchaseVms"));
				answer = (String) inFromServer.readObject(); 
  				printStream(answer);
  	      		job = (Job) inFromServer.readObject();   				
	  		} else {
	  			outToServer.writeObject(new String("CancelVms"));
				answer = (String) inFromServer.readObject(); 
  				printStream(answer);			  			
	  		}

			//close socket
			outToServer.close();
			inFromServer.close();
		  	clientSocket.close();		

		} catch (ConnectException e) {
	        	System.err.println("pid" + " must refer to a valid socket");
	        	System.exit(1);
		} catch (ClassNotFoundException e) {
        	System.err.println("Object class incompatable"+e);
        	System.exit(1);
	        	
		}				

 	}
 	public static Job createJob() {
 		Job job= new Job();
 		
 		int ntasks=5;
 		int [] cpuNum ={3,2,5,4,2};
 		int [] memSize ={1,2,4,1,2};
 		int [] fileSize ={10,2,10,1,5};
 		int [] lanSize ={2,2,2,2,2};
 		for (int i=0; i<ntasks; i++) {
 			TaskObj task = new TaskObj(i,memSize[i],cpuNum[i],fileSize[i],lanSize[i]);
 			job.tasks.add(task);
 		}
 		
 		return job;
 	}
 	public static void printStream(String answer)
 	{
 		answer=answer.replaceAll("#", "\n");
 		System.out.println(answer);

 	}
}
